package com.yongqi.pub;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

public class MySQLBackUpUtil {
	/**
	 * 数据库表备份
	 * @param dbUser
	 * @param dbPass
	 * @param dbHost
	 * @param dbPort
	 * @param dbName
	 * @param savePath
	 * @param tableName
	 * @throws Exception
	 */
	public static void databaseBackUp(String dbHost,String dbUser,String dbPass,String dbPort,String dbName,String fileName,String savePath) throws Exception{
		File saveFile = new File(savePath);
		if (!saveFile.exists()) {	//不存在此目录
			saveFile.mkdir();	//创建文件夹
		}
		PrintWriter printWriter = null;
		BufferedReader bufferedReader = null;
		try {
			printWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(savePath+fileName),"utf8"));
			//	/usr/bin/mysqldump -h 123.206.113.157 -udamionew -pAragakiYui@3306 design
			//	mysql -u damionew -pAragakiYui@3306 -h 123.206.113.157 -P 3306 -D design
			// 	mysqldump -u damionew -pAragakiYui@3306 --default-character-set=utf8 -h 123.206.113.157 -P 3306 design
			String cmdString = "cmd /c mysqldump -u "+dbUser+" -p"+dbPass+" -h "+dbHost+" -P "+dbPort+" "+dbName;
			System.out.println(cmdString);
			Runtime runtime = Runtime.getRuntime();
			Process process = runtime.exec(cmdString);
			InputStreamReader inputStreamReader = new InputStreamReader(process.getInputStream(),"utf8");
			bufferedReader = new BufferedReader(inputStreamReader);
			String line;
			while((line = bufferedReader.readLine())!=null) {
				printWriter.println(line);
			}
			printWriter.flush();
			if (process.waitFor() == 0) {
				System.out.println("数据库备份成功！");
			}
		} catch (Exception e) {
			System.out.println("数据库备份失败！");
			e.printStackTrace();
		}finally {
			try {
				if (bufferedReader != null) {
					bufferedReader.close();
				}
				if (printWriter != null) {
					printWriter.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
